package com.aw.datajpa.api;

;
import com.aw.datajpa.pojo.Student;
import com.aw.datajpa.service.StudentService;
import com.aw.datajpa.until.RUtil;
import com.aw.datajpa.vo.QueryObj;
import com.aw.datajpa.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/student")
public class StudentApiController {
    @Autowired
    public StudentService studentService;
    @GetMapping("/list")
    public R<List<Student>> findAll(Model model) {
        List<Student> students = studentService.getAll();
        model.addAttribute("students", students); // 确保这行取消注释
        return RUtil.success(students);
    }
    @PostMapping("/add")
    public R<Student> add(@RequestBody Student student) { // 添加@RequestBody
        return RUtil.success(studentService.add(student));
    }

    @PutMapping("/update")
    public R<Student> update(@RequestBody Student student) { // 添加@RequestBody
        return RUtil.success(studentService.update(student));
    }
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        studentService.delete(id);
        return RUtil.success();
    }
    @GetMapping("/validateUser")
    public R validateSnoAndPassword(String sno, String password) throws Exception {
        return RUtil.success(studentService.validateUsernameAndPassword(sno, password));
    }
    @PostMapping("/getbyPage")
    @GetMapping("/getbyPage")
    public R<Page<Student>> getbyPage(@RequestBody QueryObj<Student> qObj) {

        // 按id倒序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Integer pageIndex = qObj != null && qObj.getPageIndex() != null ? qObj.getPageIndex() : 0;
        Integer pageSize = qObj != null && qObj.getPageSize() != null ? qObj.getPageSize() : 10;

        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

        if (qObj != null && qObj.getData() != null) {
            Student student = qObj.getData();
            // 创建匹配器，支持多属性查询
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("number", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("sex", ExampleMatcher.GenericPropertyMatchers.exact())
                    .withMatcher("age", ExampleMatcher.GenericPropertyMatchers.exact())
                    .withIgnoreNullValues();

            Example<Student> example = Example.of(student, matcher);
            Page<Student> studentPage = studentService.getAll(example, pageable);
            return RUtil.success(studentPage);
        } else {
            // 无查询条件，直接返回所有分页数据
            Page<Student> students = studentService.getAll(pageable);
            return RUtil.success(students);
        }
    }
}
